package com.llx.use;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import com.llx.use.thread.CalcThreadPool;
import com.llx.use.thread.IOThreadPool;
import com.llx.use.thread.Run;

/**
 * @author : Linxu
 * @create : 2021/9/16
 * @update : 2023/2/20
 *            ^__^
 *            (**)\ _ __ _
 *            (__)\       )\/\
 *             U  ||------|
 *                ||     ||
 * ==============================
 * @desc   : 线程池,执行子线程
 */
public class Threads {

    private static final HandlerThread mHandlerThread = new HandlerThread("Thread BackGround");
    private static final Handler mBackHandler;
    private static final Handler mUIHandler;

    static {
        mHandlerThread.start();
        mBackHandler = new Handler(mHandlerThread.getLooper());
        mUIHandler = new Handler(Looper.getMainLooper());
    }

    public static boolean isMain() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    public static void ui(Runnable runnable) {
        if (isMain()) runnable.run();
        else {
            mUIHandler.post(runnable);
        }
    }

    public static void ui(Runnable runnable, int delayMillis) {
        if (delayMillis > 0) {
            mUIHandler.postDelayed(runnable, delayMillis);
        } else {
            mUIHandler.post(runnable);
        }
    }

    public static void back(Runnable runnable) {
        mBackHandler.post(runnable);
    }

    public static void back(Runnable runnable, int delayMillis) {
        if (delayMillis > 0) {
            mBackHandler.postDelayed(runnable, delayMillis);
        } else {
            mBackHandler.post(runnable);
        }
    }

    public static void io(Runnable runnable) {
        IOThreadPool.execute(runnable);
    }

    public static void io(Run runnable, int delayMillis) {
        Threads.io(() -> {
            do {
                runnable.loop ++;
                Threads.sleep(delayMillis);
                if (runnable.stop) return;
                if (!runnable.loop()) {
                    runnable.run();
                    runnable.loop = 0;
                    return;
                }
            } while (runnable.loop());
        });
    }

    public static void calc(Runnable runnable) {
        CalcThreadPool.execute(runnable);
    }

    /**
     * 延时
     * @param delayMillis
     */
    public static void sleep(long delayMillis){
        try {
            Thread.sleep(delayMillis);
        } catch (InterruptedException e) {
            // 重设中断标志位为true
            Thread.currentThread().interrupt();
            e.printStackTrace();
        }
    }

    public static void remove(Runnable runnable) {
        mUIHandler.removeCallbacks(runnable);
        mBackHandler.removeCallbacks(runnable);
        IOThreadPool.cancel(runnable);
        CalcThreadPool.cancel(runnable);
        if (runnable instanceof Run) ((Run)runnable).stop();
    }

}
